package cn.com.dycc.infomation_center.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.dycc.common.attach.dao.AttachDao;
import cn.com.dycc.common.attach.entity.Attach;
import cn.com.dycc.common.entity.DeleteEntity;
import cn.com.dycc.common.log.Constants;
import cn.com.dycc.common.log.SystemServiceLog;
import cn.com.dycc.infomation_center.dao.Pb_Party_InformationDao;
import cn.com.dycc.infomation_center.entity.Pb_Party_Information;
import cn.com.dycc.infomation_center.param.Pb_Party_InformationParam;
import cn.com.dycc.sys_manage.dictionarysysmanagement.dao.DictionaryDao;
import cn.com.dycc.sys_manage.dictionarysysmanagement.entity.DictionaryResult;
import cn.com.dycc.util.AttachUtil;
import cn.com.dycc.util.DateUtil;
import cn.com.dycc.util.FileUtil;
import cn.com.dycc.util.JsonObjectResult;
import cn.com.dycc.util.PageObjectUtil;
import cn.com.dycc.util.PropertiesUtil;
import cn.com.dycc.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service("pb_Party_InformationService")
@Transactional
public class Pb_Party_InformationServiceImpl implements Pb_Party_InformationService{

	@Resource
	private Pb_Party_InformationDao pb_Party_InformationDao;
	@Resource
	private AttachDao attachDao;
	
	@Resource
	private DictionaryDao dictionaryDao;
	
	@SystemServiceLog(description=Constants.PARTY_INFORMATION_ADD)
	public int addPb_Party_Information(Pb_Party_InformationParam param, HttpServletRequest request)
			throws Pb_Party_InformationNotFoundException {
		checkParam(param);
		HttpSession session=request.getSession();
		String opt_user_id=(String)session.getAttribute("id");
		String create_date=DateUtil.getNowTimestamp().toString();
		String org_id=(String)session.getAttribute("org_id");
		param.setOpt_user_id(opt_user_id);
		param.setCreate_date(create_date);
		param.setState("Y");
		param.setOrg_id(org_id);
		List<Pb_Party_Information> lists = getServiceList(param);
		Pb_Party_Information entity=lists.get(0);
		int d = pb_Party_InformationDao.savePb_Party_Information(entity);
		if(d>0){
			System.out.println(param.getAttachs());
			if(param.getAttachs()!=null&&!param.getAttachs().trim().isEmpty()){
				saveT_Attach(param.getAttachs(),entity,AttachUtil.party_information_attach_type);
			}
			
			if(param.getThumbnails()!=null&&!param.getThumbnails().trim().isEmpty()){
				saveT_Attach(param.getThumbnails(),entity,AttachUtil.party_information_lst_attach_type);
			}
			
		}
		
		return d;
		
	}

	@SystemServiceLog(description=Constants.PARTY_INFORMATION_DELETE)
	public int deletePb_Party_Information(String[] attrStrs, HttpServletRequest request)
			throws Pb_Party_InformationNotFoundException {
		if (attrStrs == null) {
			throw new Pb_Party_InformationNotFoundException("请选择要删除的党建资讯信息");
		}
		HttpSession session=request.getSession();
		DeleteEntity deleteEntity=new DeleteEntity();
		String org_id=(String)session.getAttribute("org_id");
		deleteEntity.setInfo_ids(attrStrs);
		deleteEntity.setOrg_id(org_id);
		int d = pb_Party_InformationDao.deletePb_Party_Information(deleteEntity);
		return d;

	}

	@SystemServiceLog(description=Constants.PARTY_INFORMATION_UPDATE)
	public int updatePb_Party_Information(Pb_Party_InformationParam param, HttpServletRequest request)
			throws Pb_Party_InformationNotFoundException {
		//System.out.println("更新资讯信息111111111111111");
		checkParam(param);
		if (param.getInfo_id() == null || param.getInfo_id().trim().isEmpty()) {
			throw new Pb_Party_InformationNotFoundException("请选择要修改的党建资讯信息");
		}
		HttpSession session=request.getSession();
		String update_user_id=(String)session.getAttribute("id");
		String org_id=(String)session.getAttribute("org_id");
		String update_date=DateUtil.getNowTimestamp().toString();
		param.setUpdate_user_id(update_user_id);
		param.setUpdate_date(update_date);
		param.setOrg_id(org_id);
		List<Pb_Party_Information> lists = getServiceList(param);
		int d = pb_Party_InformationDao.updatePb_Party_Information(lists);
		if(d>0){
			Pb_Party_Information entity=new Pb_Party_Information();
			entity.setInfo_id(param.getInfo_id());
			entity.setUpdate_user_id((String)request.getSession().getAttribute("id"));
			entity.setUpdate_date(DateUtil.getNowTimestamp());
			entity.setOrg_id((String)request.getSession().getAttribute("org_id"));
			entity.setOpt_user_id((String)request.getSession().getAttribute("id"));
			//System.out.println("attachs:"+param.getAttachs());
			if(param.getAttachs()!=null&&!param.getAttachs().trim().isEmpty()){
				saveT_Attach(param.getAttachs(),entity,AttachUtil.party_information_attach_type);
			}
			//System.out.println("thumbnails:"+param.getThumbnails());
			if(param.getThumbnails()!=null&&!param.getThumbnails().trim().isEmpty()){
				List<Attach> attachList=attachDao.findAttachByMesNoAndType(param.getInfo_id(),Integer.valueOf(AttachUtil.party_information_lst_attach_type),org_id);
				if(attachList.size()>0){
					Attach attach=attachList.get(0);
					AttachUtil.removeFile(attach.getAttach_path());
					attachDao.deleteAttach(attach);
				}
				
				saveT_Attach(param.getThumbnails(),entity,AttachUtil.party_information_lst_attach_type);
			}
		}
		return d;
	}

	public JsonObjectResult findPb_Party_InformationByParam(Pb_Party_InformationParam param,
			HttpServletRequest request) throws Pb_Party_InformationNotFoundException {
		List<Pb_Party_Information> lists = new ArrayList<Pb_Party_Information>();
		
		checkParam(param);
		param = realParam(param, request);
		String count = pb_Party_InformationDao.getPb_Party_InformationCountByParam(param);
		
		if ("0".equals(count)) {			
			return new JsonObjectResult(lists);
		}
		param = (Pb_Party_InformationParam) PageObjectUtil.getSqlPageObject(count, param);
		lists = pb_Party_InformationDao.findPb_Party_InformationByParam(param);
		
		
		return new JsonObjectResult(count,lists);
	}
	
	/**
	 * 实际参数
	 * 
	 * @param param
	 * @param request
	 * @return
	 */
	public Pb_Party_InformationParam realParam(Pb_Party_InformationParam param, HttpServletRequest request) {
		if(param.getContent()!=null&&!param.getContent().trim().isEmpty()){
			param.setContent(StringUtil.format_mh_str(param.getContent()));
		}
		if(param.getTitle()!=null&&!param.getTitle().trim().isEmpty()){
			param.setTitle(StringUtil.format_mh_str(param.getTitle()));
		}
		
		if(param.getOrder()==null||param.getOrder().isEmpty()||"1".equals(param.getOrder())){
			param.setOrder("p.create_date desc");
		}else if("2".equals(param.getOrder())){
			param.setOrder("p.create_date asc");
			
		}else{
			param.setOrder(null);//手动防止SQL注入
		}
		return param;
	}
	
	/**
	 * 校验 @param param @return @throws
	 */
	public void checkParam(Pb_Party_InformationParam param) {
		if (param == null) {
			throw new Pb_Party_InformationNotFoundException("未登录或超时,请重新登录");
		}

	}

	public List<Pb_Party_Information> getServiceList(Pb_Party_InformationParam param)  {
		Pb_Party_Information entity = new Pb_Party_Information();
		System.out.println(param);
		entity.setInfo_id(param.getInfo_id());
		entity.setTitle(param.getTitle());
		entity.setInfo_type(param.getInfo_type());
		if(param.getContent()!=null&&!param.getContent().trim().isEmpty()){
			try {
				
				entity.setContent(StringUtil.decode(param.getContent()));
			} catch (UnsupportedEncodingException e) {
				throw new Pb_Party_InformationNotFoundException("服务器繁忙稍后再试");
			}
		}
		
		entity.setState(param.getState());
		entity.setOrg_id(param.getOrg_id());
		if(param.getCreate_date()!=null&&!param.getCreate_date().trim().isEmpty()){
			entity.setCreate_date(Timestamp.valueOf(param.getCreate_date()));
		}
		entity.setOpt_user_id(param.getOpt_user_id());
		if(param.getUpdate_date()!=null&&!param.getUpdate_date().trim().isEmpty()){
			entity.setUpdate_date(Timestamp.valueOf(param.getUpdate_date()));
		}
		entity.setUpdate_user_id(param.getUpdate_user_id());
		
		List<Pb_Party_Information> lists = new ArrayList<Pb_Party_Information>();
		lists.add(entity);
		return lists;
	}
	
	/**
	 * 将临时目录下的文件移到正式目录
	 */
	private void saveT_Attach(String attachInfos,Pb_Party_Information entity,String attach_type){
		List<Attach> listAttach=new ArrayList<Attach>();
		
		if(attachInfos!=null&&!attachInfos.trim().isEmpty()){
			
			String str=attachInfos.trim();
			
			JSONArray json=JSONArray.fromObject(str);
			
			for(int i=0;i<json.size();i++){
				
				Object check=json.get(i);
				
				
				if("null".equals(check.toString())){
					continue;
				}
				JSONObject job = json.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象			
				String attach_ext=(String)job.get("attach_ext");
				String attach_path=(String)job.get("attach_path");
				String attach_size=(String)job.get("attach_size");
				String title=(String)job.get("title");
				
				Attach attach=new Attach();
				attach.setMessage_no(entity.getInfo_id());
				attach.setAttach_type(Integer.valueOf(attach_type));
				attach.setTitle(title);
				attach.setAttach_ext(attach_ext);
				attach.setAttach_path(attach_path);
				attach.setAttach_size(attach_size);				
				attach.setOrg_id(entity.getOrg_id());
				attach.setOpt_user_id(entity.getOpt_user_id());
				
				attach.setCreate_date(DateUtil.getNowTimestamp());
				
				listAttach.add(attach);			
			}
		}
		
		
		List<Attach> newListAttach=FileUtil.moveFile(listAttach,"infomation_center");
		
		if(newListAttach!=null){
			for(Attach attach:newListAttach){
				
				attachDao.insertAttach(attach);
			}
						
		}
		
	}

	public JsonObjectResult findNewPb_Party_Information(HttpServletRequest request)
			throws Pb_Party_InformationNotFoundException, IOException {
		HttpSession session=request.getSession();
		String org_id=(String)session.getAttribute("org_id");
		List<DictionaryResult> list=dictionaryDao.dicList(org_id, null, null, "pb_party_information", "info_type", null, null);
		Map<String,Object> map=new HashMap<String, Object>();
		for(int i=0;i<list.size();i++){
			String key=list.get(i).getKey();
			String remake=list.get(i).getRemake();
			String key1=null;
			if(remake==null||remake.trim().isEmpty()){
				key1="info_type"+key;
			}else{
				key1=remake;
			}
			Pb_Party_InformationParam param=new Pb_Party_InformationParam();
			String count=PropertiesUtil.readProperties("db/config.properties", "special_activity_count");
			param.setOrg_id(org_id);
			param.setInfo_type(key);
			param.setStart(0);
			param.setEnd(Integer.valueOf(count));
			
			param.setOrder("p.create_date desc");
			List<Pb_Party_Information> list2=pb_Party_InformationDao.findPb_Party_InformationByParam(param);
			for(int j=0;j<list2.size();j++){
				Pb_Party_Information party_Information=list2.get(j);
				party_Information.setContent(StringUtil.deleteLable(party_Information.getContent()));
				list2.set(j, party_Information);
				
			}
			map.put(key1, list2);
		}
		return new JsonObjectResult(map);
	}

	

}
